/*
This file is part of IRCaBot.
IRCaBot is IRC logger with features.
Source code: https://notabug.org/acetone/ircabot.
Copyright (C) acetone, 2023.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#include "token.h"
#include "random.h"

#include <QCryptographicHash>
#include <QDebug>

constexpr const int SIGNATURE_SECRET_LENGTH = 64;

QString Token::m_signatureSecret;

Token::Token(const QStringList &payload)
{
    if (m_signatureSecret.isEmpty())
    {
        m_signatureSecret = randomString(SIGNATURE_SECRET_LENGTH);
    }
    m_payload = payload;
    QString payloadString = payload.join(':');
    QString hash = shortHash(payloadString.toUtf8() + m_signatureSecret.toUtf8());
    m_token = (payloadString+":"+hash).toUtf8().toBase64(QByteArray::Base64Option::Base64UrlEncoding |  QByteArray::Base64Option::OmitTrailingEquals);
    m_valid = true;
}

Token::Token(const QString &base64Token)
{
    m_token = base64Token;

    QStringList raw = QString(QByteArray::fromBase64(base64Token.toUtf8(), QByteArray::Base64Option::Base64UrlEncoding | QByteArray::Base64Option::OmitTrailingEquals)).split(':');
    if (raw.size() < 2)
    {
        qDebug() << "Received invalid token in Token (wrong structure). Rejected.";
        return;
    }

    QString passedHash = raw.last();
    raw.pop_back();
    m_payload = raw;

    QString payloadString = raw.join(':');
    QString hash = shortHash(payloadString.toUtf8() + m_signatureSecret.toUtf8());
    if (hash != passedHash)
    {
        qDebug() << "Received invalid token in Token (wrong signature). Rejected.";
        return;
    }
    m_valid = true;
}

QString Token::shortHash(const QByteArray &data, uint8_t shortFactor)
{
    if (shortFactor == 0)
    {
        qCritical() << "Invalid call of Token::shortHash with shortFactor(0)! (zero division)";
    }

    const QString original = QCryptographicHash::hash(data, QCryptographicHash::Md5)
            .toBase64(QByteArray::Base64Option::Base64UrlEncoding | QByteArray::Base64Option::OmitTrailingEquals);
    QString result;
    for (uint8_t i = 0; i < original.size(); ++i)
    {
        if (i % shortFactor == 0)
        {
            result.push_back(original.at(i));
        }
    }
    return result;
}

